<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

class BaseController extends Controller
{

    // 初始化
    public function initialize()
    {
        $opt = $this->optLogic();
        // 必须登录：个人中心
        $action     = $opt->getData('action', null, 'trim');
        $controller = $opt->getData('controller', null, 'trim');
        $controller = strtolower($controller);
        // 获取用户信息
        //  登录。获取token的时候，不需要登录
        $user = [];
        if(($controller == 'account') && (in_array($action, ['login', 'token', 'captcha', 'click', 'checkClick']))){

        } else{
            $user = $this->myUser();
        }
        if($controller == 'profile'){
            $opt->throwIf(empty($this->myUser), 'please_login_before_operation', LOGIN_ERROR);
        }

        parent::initialize();
    }

    // 获取用户以及权限 session
    protected function myUser2()
    {
        $option = $this->optLogic();
        $info   = $option->session();
        if($info === false){
            //$option->throwIf(empty($user), $option->getError(), $option->getCode());
            return $info;
        }
        if(empty($info)){
            return $info;
        }
        // 组合
        $info['uid']  = $info['id'];
        $this->myUid  = $info['id'];
        $this->myUser = $info;
        $option->assign('myUser', $info);

        return $info;
    }

    // 获取用户以及权限
    protected function myUser()
    {
        $option     = $this->optLogic();
        $action     = $option->getData('action', null, 'trim');
        $controller = $option->getData('controller', null, 'trim');
        $controller = strtolower($controller);

        // 获取用户信息
        $info = $option->token('user-token');

        // 如果获取失败，会提示重新登录
        //  但一般页面可以展示，则不提示错误信息
        if($controller == 'profile'){
            if($info === false){
                $option->throwIf(empty($user), $option->getError(), $option->getCode());
            }
        }

        if(empty($info)){
            return $info;
        }

        $info['card_date_date'] = $info['card_date'] ? date('Y-m-d', $info['card_date']) : '';
        $info['card_date_show'] = $info['card_date'] ? date('m/y', $info['card_date']) : '';
        // 组合
        $info['uid']   = $info['id'];
        $info['first'] = substr($info['email'], 0, 1);
        $this->myUid   = $info['id'];
        $this->myUser  = $info;

        return $info;
    }
}


